package com.allenyuan.gui;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JProgressBar;
import javax.swing.JTextArea;

import com.allenyuan.carvingsocketclient.AsyncSocketClient.ProgressListener;
import com.allenyuan.carvingsocketclient.RemotingMethod;
import com.allenyuan.proto.GCodeOperation.GCodePackageResult;
import com.allenyuan.proto.PrintTask.AppendPrintTaskResult;
import com.allenyuan.proto.PrintTask.GetPrintTaskPositionResult;
import com.allenyuan.proto.PrintTask.PrintTaskType;
import com.allenyuan.proto.TestPbProto.TestPb;
import com.google.protobuf.Message;

import javax.swing.BorderFactory;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.awt.Graphics;

public class PrintProgressPanel extends AbstractPanel {



	/**
	 * 
	 */
	private static final long serialVersionUID = -261082109314600354L;
	
	private JProgressBar progressBar;
	private JLabel progressText;
	private JTextArea textArea;

	/**
	 * Create the panel.
	 */
	public PrintProgressPanel(GuiContext context) {
		super(context);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{150, 0, 0};
		gridBagLayout.rowHeights = new int[]{30, 25, 24, 0};
		gridBagLayout.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
		optionPanel.setLayout(gridBagLayout);
		
		progressBar = new JProgressBar();
		progressBar.setValue(0);
		GridBagConstraints gbc_progressBar = new GridBagConstraints();
		gbc_progressBar.fill = GridBagConstraints.BOTH;
		gbc_progressBar.insets = new Insets(0, 0, 5, 5);
		gbc_progressBar.gridx = 0;
		gbc_progressBar.gridy = 0;
		optionPanel.add(progressBar, gbc_progressBar);
		
		progressText = new JLabel("0%");
		GridBagConstraints gbc_progressText = new GridBagConstraints();
		gbc_progressText.insets = new Insets(0, 0, 5, 0);
		gbc_progressText.gridx = 1;
		gbc_progressText.gridy = 0;
		optionPanel.add(progressText, gbc_progressText);
		
		JLabel label = new JLabel("详细信息：");
		label.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		GridBagConstraints gbc_label = new GridBagConstraints();
		gbc_label.anchor = GridBagConstraints.SOUTHWEST;
		gbc_label.insets = new Insets(0, 0, 5, 5);
		gbc_label.gridx = 0;
		gbc_label.gridy = 1;
		optionPanel.add(label, gbc_label);
		
		textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setLineWrap(true);
		textArea.setBorder(BorderFactory.createEtchedBorder());
		GridBagConstraints gbc_textArea = new GridBagConstraints();
		gbc_textArea.gridwidth = 2;
		gbc_textArea.fill = GridBagConstraints.BOTH;
		gbc_textArea.gridx = 0;
		gbc_textArea.gridy = 2;
		optionPanel.add(textArea, gbc_textArea);
		// TODO Auto-generated constructor stub
		
	}
	
	private boolean hasStart = false;
	@Override
	public void paint(Graphics g) {
		// TODO Auto-generated method stub
		super.paint(g);
		if (!hasStart) {
			new Thread(new PrintProgressRunnable(this, textArea, progressBar, progressText, getContext())).start();
			hasStart = true;
		}
	}
	
	public class PrintProgressRunnable implements Runnable {
		
		private JTextArea textArea;
		private JLabel progressText;
		private JProgressBar progressBar;
		private GuiContext context;
		private PrintProgressPanel panel;
		
		private int totalPackages;
		private int currentPackage;
		
		public PrintProgressRunnable(PrintProgressPanel panel, JTextArea textArea, JProgressBar progressBar, JLabel progressText, GuiContext context) {
			super();
			this.textArea = textArea;
			this.progressBar = progressBar;
			this.context = context;
			this.progressText = progressText;
			this.panel = panel;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			System.out.println("start");
			while (!panel.isVisible()) {}
			System.out.println("start");
			File file = new File("D:\\test.txt");
			List<String> content = new ArrayList<String>();

			BufferedReader in = null;
			String line = null;
			try {
				in = new BufferedReader(new FileReader(file));
				while((line = in.readLine()) != null) {
					if (!line.trim().isEmpty()) {
						content.add(line);
						System.out.println(line);
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				textArea.append("文件未找到...\n");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				textArea.append("文件读取错误...\n");
				return;
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
			totalPackages = content.size() / 10 + ((content.size() % 10 == 0) ? 0 : 1);
			currentPackage = 0;
			
			textArea.append("测试连接...");
			RemotingMethod.TestPb(10, new ProgressListener() {
				
				@Override
				public void received(Message message) {
					// TODO Auto-generated method stub
					TestPb test = (TestPb) message;
					if (test != null && test.getTest() == 10) {
						textArea.append("成功\n");
						textArea.append("正在添加打印任务...");
						RemotingMethod.AppendPrintTask(PrintTaskType.PRINT_TASK_GCODE, 100, 100, false, new ProgressListener() {
							
							@Override
							public void received(Message message) {
								// TODO Auto-generated method stub
								AppendPrintTaskResult appendPrintTaskResult = (AppendPrintTaskResult) message;
								if (appendPrintTaskResult != null && appendPrintTaskResult.getIsSuccess()) {
									textArea.append("成功\n");

									RemotingMethod.GetPrintTaskPosition(appendPrintTaskResult.getTaskId(), new ProgressListener() {
										
										private GetPrintTaskPositionResult getPrintTaskPositionResult; 
										
										@Override
										public void received(Message message) {
											// TODO Auto-generated method stub
											getPrintTaskPositionResult = (GetPrintTaskPositionResult) message;
											if (getPrintTaskPositionResult != null && getPrintTaskPositionResult.getIsSuccess()) {
												if (getPrintTaskPositionResult.getTaskPosition() != 0) {
													try {
														Thread.sleep(5000);
													} catch (InterruptedException e) {
														// TODO Auto-generated catch block
														e.printStackTrace();
													}
													int now = getPrintTaskPositionResult.getTaskPosition();
													if (now != currentPackage) {
														currentPackage = now;
														textArea.append("你的任务排在第" + (getPrintTaskPositionResult.getTaskPosition() + 1) + "位\n");
													}
													RemotingMethod.GetPrintTaskPosition(appendPrintTaskResult.getTaskId(), this);
												}
												else {
													JOptionPane.showMessageDialog(PrintProgressPanel.this, "请用户手动调整激光头的位置至坐标原点，即雕刻面的左上角，然后点击确定。", "对刀", JOptionPane.INFORMATION_MESSAGE);
													textArea.append("雕刻任务开始\n");
													RemotingMethod.GCodePackage(content.subList(currentPackage * 10, (((currentPackage + 1) * 10) < content.size() ? (currentPackage + 1) * 10 : content.size() - 1)), currentPackage, totalPackages, appendPrintTaskResult.getTaskId(), new ProgressListener() {
														
														@Override
														public void received(Message message) {
															// TODO Auto-generated method stub
															GCodePackageResult gCodePackageResult = (GCodePackageResult) message;
															if (gCodePackageResult != null && gCodePackageResult.getResult()) {
																currentPackage++;
																progressBar.setValue(currentPackage * 100 / totalPackages);
																progressText.setText(String.valueOf(currentPackage * 100 / totalPackages) + "%");
																if (currentPackage == totalPackages) {
																	textArea.append("雕刻任务完成\n");
																	return;
																}
																
																try {
																	Thread.sleep(5000);
																} catch (InterruptedException e) {
																	// TODO Auto-generated catch block
																	e.printStackTrace();
																	return;
																}
																RemotingMethod.GCodePackage(content.subList(currentPackage * 10, (((currentPackage + 1) * 10) < content.size() ? (currentPackage + 1) * 10 : content.size() - 1)), currentPackage, totalPackages, appendPrintTaskResult.getTaskId(), this);
																
															} 
															else if (gCodePackageResult != null && (!gCodePackageResult.getResult())) {
																try {
																	Thread.sleep(5000);
																} catch (InterruptedException e) {
																	// TODO Auto-generated catch block
																	e.printStackTrace();
																}
																RemotingMethod.GCodePackage(content.subList(currentPackage * 10, (((currentPackage + 1) * 10) < content.size() ? (currentPackage + 1) * 10 : content.size() - 1)), currentPackage, totalPackages, appendPrintTaskResult.getTaskId(), this);
															}
															else  {
																textArea.append("发送数据包失败...\n");
															}
														}
														
														@Override
														public void connected(boolean success) {
															// TODO Auto-generated method stub
															if (!success) {
																textArea.append("发送数据包失败...失败\n");
															}
														}
													});
												}
											}
											else {
												textArea.append("获取排队信息...失败\n");
											}
										}
										
										@Override
										public void connected(boolean success) {
											// TODO Auto-generated method stub
											if (!success) {
												textArea.append("获取排队信息...失败\n");
											}
										}
									});
								}
								else {
									textArea.append("失败\n");
								}
							}
							
							@Override
							public void connected(boolean success) {
								// TODO Auto-generated method stub
								if (!success) {
									textArea.append("失败\n");
								}
							}
						});
					}
					else {
						textArea.append("失败\n");
					}
				}
				
				@Override
				public void connected(boolean success) {
					// TODO Auto-generated method stub
					if (!success) {
						textArea.append("失败...\n");
					}
				}
			});
			
		}
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected String getGuideText() {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("现在本雕刻机开始进行雕刻作业，以下将显示雕刻的进度。");
		return sb.toString();
	}

	@Override
	protected String getGuideTitle() {
		// TODO Auto-generated method stub
		return "正在进行雕刻";
	}

}
